# Create your views here.
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
import RouteGenerator, updateDB, util
import datetime

color = ['#0000ff', '#ff0000', '#00ff00', '#ffff00', '#00ffff', '#ff00ff', '#000000',
         '#33ff99', '#ff3399', '#9933ff', '#3399ff', '#ff9933', '#99ff33', '#6699cc']

oldWeight = 0.5
oldSimLmt = 0.05
oldNumRoutes = 2
oldStart  = 'enter start address'
oldEnd    = 'enter end address'
oldNoise  = 'yes'
oldMode   = 'car'
oldRoutes = []
oldProjID = None
oldTable  = None
sbuser    = None
sbpw    = None

def view_route(request):
    global oldWeight, oldSimLmt, oldNumRoutes, oldStart, oldEnd, oldNoise, oldMode, oldRoutes, oldProjID, oldTable, sbpw, sbuser
    
    if request.POST:
        if request.POST['option'] == 'search':
            RouteGenerator.setConfig()
            updateDB.setConfig()
                
            oldStart = start     = request.POST['start']
            oldEnd   = end       = request.POST['end']
            startTime = request.POST['startTime']
            oldNoise = noise     = request.POST['noise']
            oldMode  = modeOfT   = request.POST['modeOfT']
            
            if start == '' or end == '':
                return render_to_response('route/main.html', {'show_map':False, 'start':start, 'end':end, 'numRoutes':request.POST['numRoutes'],
                                                              'msg':'Bad input', 'weight':request.POST['weight']})
            if request.POST['numRoutes'] != '' and util.isanum(request.POST['numRoutes']) == 1:
                oldNumRoutes = eval(request.POST['numRoutes'])
            numRoutes = oldNumRoutes
                
            if request.POST['weight'] != '' and util.isanum(request.POST['weight']) == 1:
                oldWeight = eval(request.POST['weight'])
                RouteGenerator.changeWeight(oldWeight)
            weight = oldWeight
                
            if request.POST['simLmt'] != '' and util.isanum(request.POST['simLmt']) == 1 and type(eval(request.POST['simLmt'])) is float:
                oldSimLmt = eval(request.POST['simLmt'])
                RouteGenerator.changeSimLmt(oldSimLmt)
            simLmt = oldSimLmt
                
            noisy = True
            if request.POST['noise'] == 'yes':
                noisy = True
            else:
                noisy = False
                
            routes = RouteGenerator.generateRoutesToDjango(numRoutes, start, end, modeOfT = request.POST['modeOfT'], noise = noisy)
            
            if len(routes) == 0:
                return render_to_response('route/main.html', {'show_map':False, 'start':start, 'end':end, 'numRoutes':numRoutes,
                                                              'msg':'bad address', 'weight':weight, 'simLmt':simLmt})
            elif routes[0] != 0:
                return render_to_response('route/main.html', {'show_map':False, 'start':start, 'end':end, 'numRoutes':numRoutes,
                                                              'msg':'address alternatives', 'weight':weight, 'simLmt':simLmt,
                                                              'altAddr':routes[1]})
            else:
                routes.pop(0)
                oldRoutes = routes[0]

            if len(routes) == 0:
                return render_to_response('route/main.html', {'show_map':False, 'start':start, 'end':end, 'numRoutes':numRoutes,
                                                              'msg':'Bad address', 'weight':weight, 'simLmt':simLmt,
                                                              'modeOfT' : request.POST['modeOfT'], 'noise' : request.POST['noise']})
            center = routes[0][0][0]
    
            return render_to_response('route/main.html', {'show_map':True, 'start':start  , 'end': end, 'processTime':routes[1],
                                                           'start':start, 'end':end, 'numRoutes':numRoutes, 'weight':weight, 'arrayRoutes':routes[0], 
                                                           'colors':color, 'center':center, 'startTime': datetime.datetime.now(), 'simLmt':simLmt,
                                                           'modeOfT' : request.POST['modeOfT'], 'noise' : request.POST['noise'],
                                                           'projID' : oldProjID, 'table':oldTable, 'sbuser':sbuser, 'sbpw':sbpw })

        elif request.POST['option'] == 'update':
            if request.POST['changeAddr'] != '' and (request.POST['ranking'] != '' or 'unavailableCars' in request.POST or 'unavailableBikes' in request.POST):
                newAddr = request.POST['changeAddr']
                if request.POST['ranking'] != '' and type(eval(request.POST['ranking'])) == int:
                    updateDB.markRouteRating(newAddr, eval(request.POST['ranking']))
                elif 'unavailableCars' in request.POST:
                    updateDB.markRouteAvailability(newAddr, 'car', eval(request.POST['unavailableCars']))
                elif 'unavailableBikes' in request.POST:
                    updateDB.markRouteAvailability(newAddr, 'bike', eval(request.POST['unavailableBikes']))
                return render_to_response('route/main.html', {'show_map':False, 'start':oldStart, 'end':oldEnd, 'numRoutes':oldNumRoutes,
                                                              'msg':'successful update', 'weight':oldWeight, 'simLmt':oldSimLmt,
                                                              'modeOfT' : oldMode, 'noise' : oldNoise})

            else:
                return render_to_response('route/main.html', {'show_map':False, 'start':oldStart, 'end':oldEnd, 'numRoutes':oldNumRoutes,
                                                              'msg':'Bad address', 'weight':oldWeight, 'simLmt':oldSimLmt,
                                                              'modeOfT' : oldMode, 'noise' : oldNoise})
        elif request.POST['option'] == 'upload':            
            oldProjID = proj_id    = request.POST['proj_id']
            oldTable  = table_name = request.POST['table_name']
            sbuser    = request.POST['sbuser']
            sbpw      = request.POST['sbpw']
            successful = True
            
            if sbuser == '' or sbpw == '':
                return render_to_response('route/main.html', {'show_map':False, 'start':oldStart, 'end':oldEnd, 'numRoutes':oldNumRoutes,
                                                              'msg': 'bad sensorbase info', 'weight':oldWeight, 'simLmt':oldSimLmt,
                                                              'modeOfT' : oldMode, 'noise' : oldNoise})
            
            if proj_id == '' or table_name == '':
                return render_to_response('route/main.html', {'show_map':False, 'start':oldStart, 'end':oldEnd, 'numRoutes':oldNumRoutes,
                                                              'msg': 'Bad project ID or table name', 'weight':oldWeight, 'simLmt':oldSimLmt,
                                                              'modeOfT' : oldMode, 'noise' : oldNoise})
            if util.isanum(proj_id) == 1:
                oldProjID = proj_id = eval(request.POST['proj_id'])
            else:
                return render_to_response('route/main.html', {'show_map':False, 'start':oldStart, 'end':oldEnd, 'numRoutes':oldNumRoutes,
                                                              'msg': 'Bad project ID', 'weight':oldWeight, 'simLmt':oldSimLmt,
                                                              'modeOfT' : oldMode, 'noise' : oldNoise})

            for num in range(oldNumRoutes):
                if request.POST.__contains__(str(num + 1)):
                    result = RouteGenerator.uploadToSensorbase(proj_id, table_name, oldRoutes[num], oldStart, oldEnd, sbuser, sbpw)
                    if result[0] != 0:
                        successful = False
                        break
            
            if successful:
                msg = 'Successfully uploaded'
            else:
                msg = 'Failed to upload', result[1]
            return render_to_response('route/main.html', {'show_map':False, 'start':oldStart, 'end':oldEnd, 'numRoutes':oldNumRoutes,
                                                              'msg': msg, 'weight':oldWeight, 'simLmt':oldSimLmt,
                                                              'modeOfT' : oldMode, 'noise' : oldNoise})

    return render_to_response('route/main.html', {'show_map':False})